/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.act.rest;

import cn.hutool.core.util.ObjectUtil;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.config.FileProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.act.domain.Activity;
import me.zhengjie.modules.act.domain.vo.PublishActVo;
import me.zhengjie.modules.act.service.ActivityService;
import me.zhengjie.modules.act.service.dto.ActivityDto;
import me.zhengjie.modules.act.service.dto.ActivityQueryCriteria;
import me.zhengjie.modules.hires.service.dto.HiresDto;
import me.zhengjie.modules.hires.service.dto.HiresQueryCriteria;
import me.zhengjie.modules.order.domain.WechatOrder;
import me.zhengjie.modules.order.service.WechatOrderService;
import me.zhengjie.modules.pay.wechat.sdk.WxPayTradeTypeEnum;
import me.zhengjie.modules.publish.service.PublishTypeMoneyService;
import me.zhengjie.modules.publish.service.dto.PublishTypeMoneyDto;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.enums.PayTypeEnum;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author maojinhui
* @date 2020-10-30
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "活动管理")
@RequestMapping("/api/activity")
public class ActivityController {

    private final ActivityService activityService;
    private final WechatOrderService wechatOrderService;
    private final PublishTypeMoneyService publishTypeMoneyService;
    private final WxPayService wxPayService;
    private final FileProperties properties;


    @Log("提交发布活动信息")
    @ApiOperation("提交发布活动信息")
    @PostMapping(value = "/publish")
    public <T> T  publish(HttpServletRequest req ,  @RequestParam("file") MultipartFile multipartFile  , @RequestParam String title ,
                          @RequestParam String des , @RequestParam int  publishTypeMoneyId)  {


        if(ObjectUtil.isNull(title) || ObjectUtil.isEmpty(title)){
            throw new BadRequestException("请填写活动标题");
        }

        if(ObjectUtil.isNull(des) || ObjectUtil.isEmpty(des)){
            throw new BadRequestException("请填写活动描述");
        }

        // 查询支付的金额对应的时间
//        int publishTypeMoneyId = publishActVo.getPublishTypeMoneyId();
        PublishTypeMoneyDto publishTypeMoneyDto = publishTypeMoneyService.findById(publishTypeMoneyId);
        //插入招聘信息
        String userId = SecurityUtils.getCurrentUserId();
        Activity activity = new Activity();

        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("图片上传失败");
        }
        activity.setUserId(userId);
        activity.setStatus(-1);
        activity.setTitle(title);
        activity.setDes(des);
        activity.setImg(file.getPath());
        activityService.create(activity);
        // 插入订单信息
        WechatOrder order = new WechatOrder();
        order.setUserId(userId);
        order.setAttach(PayTypeEnum.ACTIVITY.getType());
        order.setAttachId(activity.getId());
        order.setPublishMoneyId(publishTypeMoneyId);

        order.setBody(activity.getTitle());
        order.setSpbillCreateIp(StringUtils.getIp(req));
        order.setTotalFee(publishTypeMoneyDto.getMoney().multiply(new BigDecimal("100")).intValue());
        order.setTradeType(WxPayTradeTypeEnum.JSAPI.getTradeType());
        order.setStatus(0);
        wechatOrderService.create(order);

        // 生成支付所需参数
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setBody(order.getBody());
        request.setOutTradeNo(order.getId());
        request.setAttach(order.getAttach());
        request.setTotalFee(order.getTotalFee());
        request.setTradeType(order.getTradeType());
        request.setSpbillCreateIp(order.getSpbillCreateIp());
        request.setOpenid(SecurityUtils.getCurrentUsername());
        request.setNotifyUrl(wxPayService.getConfig().getPayScoreNotifyUrl());

        try {
//            return new ResponseEntity<>(wxPayService.createOrder(request),HttpStatus.OK);
            return wxPayService.createOrder(request);

        } catch (WxPayException e) {
            e.printStackTrace();
            log.error(e.getCustomErrorMsg(), e);
            throw new BadRequestException(StringUtils.isNotEmpty(e.getCustomErrorMsg()) ? e.getCustomErrorMsg() : StringUtils.isNotEmpty(e.getReturnMsg()) && !e.getReturnMsg().equals("OK") ? e.getReturnMsg() : e.getErrCodeDes());
        }

    }


    @GetMapping("findById")
    @Log("根据id查询招聘信息")
    @ApiOperation("查询招聘信息")
    public ResponseEntity<ActivityDto> findActivityById(ActivityQueryCriteria resources){
        return new ResponseEntity<>(activityService.findById( resources.getId()) ,HttpStatus.OK);
    }




    /**
     *sort = id,desc
     * @param criteria
     * @param pageable
     * @return
     */
    @GetMapping("listByStatus")
    @Log("根据状态查询招聘信息")
    @ApiOperation("查询招聘信息")
//    @AnonymousAccess
    public ResponseEntity<Object> queryActivitiesByStatus(ActivityQueryCriteria criteria,
                                                Pageable pageable){
        return new ResponseEntity<>(activityService.queryAll(criteria, pageable),HttpStatus.OK);
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('activity:list')")
    public void download(HttpServletResponse response, ActivityQueryCriteria criteria) throws IOException {
        activityService.download(activityService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询活动")
    @ApiOperation("查询活动")
    @PreAuthorize("@el.check('activity:list')")
    public ResponseEntity<Object> query(ActivityQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(activityService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增活动")
    @ApiOperation("新增活动")
    @PreAuthorize("@el.check('activity:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Activity resources){
        return new ResponseEntity<>(activityService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改活动")
    @ApiOperation("修改活动")
    @PreAuthorize("@el.check('activity:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Activity resources){
        activityService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除活动")
    @ApiOperation("删除活动")
    @PreAuthorize("@el.check('activity:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        activityService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}